<template>
	<view class="clock_in">
		<g-watermark/>
		<view class="clock_in_time">
			<view class="dayTime_time">
				{{dayTime.time}}
			</view>
			<view class="dayTime_day">
				<text>{{dayTime.day}}</text>
				<text style="margin-left: 20upx;">{{dayTime.week}}</text>
			</view>
		</view>
		<view class="clock_in_summary">
			<view>
				<image src="../static/clockIn/address.png" mode="" style="width:220upx;height: 220upx;"></image>
			</view>
			<view style="margin-top: 10upx;">
				有效距离 {{punchPage.radius}} 米
			</view>
		</view>
		<view class="clock_in_statistics">
			<view class="clock_in_statistics_left">
				<view class="clock_in_statistics_left_value">
					<text style="font-size: 40upx;">{{punchPage.mouthSignInCount}}</text>次
				</view>
				<view class="clock_in_statistics_left_label">
					月累计打卡
				</view>
			</view>
			<view class="clock_in_statistics_right">
				<view class="clock_in_statistics_right_value">
					<text style="color:red;font-size: 40upx;">{{punchPage.mouthAbnormalCount}}</text>次
				</view>
				<view class="clock_in_statistics_right_label">
					月迟到早退
				</view>
			</view>
		</view>
		<view style="font-size: 28upx;text-align: center;font-weight:bold;" v-if="!isDistance && location.distance">
			您目前不在打卡范围内，距离 {{Math.round(location.distance*1000)}} 米
		</view>
		<view style="font-size: 28upx;text-align: center;font-weight:bold;margin:10upx" v-if="!punchPage.isBtnGrey && isDistance">
			<text :style="{color: typeStatus==0?'green':'red'}">{{typeDesc}}</text>
		</view>
		<view class="clock_in_refresh">
			<!-- <template v-if="false">
				<view style="font-size: 32upx;font-weight:bold;">
					您目前不在打卡范围内
				</view>
				<view style="margin-top: 20upx;">
					<image src="../static/clockIn/refresh.png" mode="" style="width:130upx;height: 130upx;"
						@click="handleRefresh"></image>
				</view>
				<view style="color: #fe8e22;">
					点击刷新
				</view>
			</template> -->
			<template v-if="!punchPage.isBtnGrey && isDistance">
				<view @click="handleClock">
					<view style="margin-top: 20upx;">
						<image src="../static/clockIn/clock_active.png" mode="" style="width:130upx;height: 130upx;">
						</image>
					</view>
					<view style="color: #0293fe;">
						打卡
					</view>
				</view>
			</template>
			<template v-else>
				<view>
					<view style="margin-top: 20upx;">
						<image src="../static/clockIn/clock.png" mode="" style="width:130upx;height: 130upx;"></image>
					</view>
					<view style="color: #8a8a8a;">
						打卡
					</view>
				</view>
			</template>
		</view>
		<view class="clock_in_menu">
			<view class="clock_in_menu_box" @click="handleSelected(1)">
				<view>
					<image v-if="current==1" src="../static/clockIn/refresh.png" mode=""
						style="width:60upx;height: 60upx;"></image>
				</view>
				<view :class="{active:current==1}">
					刷新
				</view>
			</view>
			<view class="clock_in_menu_box" @click="handleSelected(2)">
				<view>
					<image v-if="current!=2" src="../static/clockIn/record.png" mode=""
						style="width:60upx;height: 60upx;"></image>
				</view>
				<view :class="{active:current==1}">
					记录
				</view>
			</view>
		</view>
		<ShowModal v-model="showOpen" title="" :mData="modalData" type="customBtn" @onConfirm="onConfirm"
			:showCancel="false" :maskEnable="false">
			<view>
				<u-form :model="valiFormData" ref="uForm">
					<u-form-item label="原因" prop="remark" required>
						<uni-easyinput type="textarea" v-model="valiFormData.remark"
							placeholder="请填写原因"></uni-easyinput>
					</u-form-item>
				</u-form>
			</view>
		</ShowModal>
	</view>
</template>

<script>
	import ShowModal from "../component/show-modal/index.vue";
	import moment from 'moment'
	import {
		getAction,
		postAction,
		postFormAction
	} from "@/utils/request.js";
	export default {
		components: {
			ShowModal
		},
		data() {
			return {
				times: null,
				dayTime: {
					time: '',
					day: '',
					week: ''
				},
				current: 1,
				location: {},
				punchPage: {},
				isDistance: false,
				typeDesc: '',
				typeStatus: 0,
				punchId: -1,
				showOpen: false,
				modalData: {
					title: "",
					confirmText: "确定",
				},
				valiFormData: {
					remark: "",
				},
				rules: {
					remark: [{
						required: true,
						message: '原因不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
				}
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		mounted() {
			this.init()
			this.initTime()
		},
		destroyed() {
			if (this.times) {
				clearInterval(this.times)
			}
		},
		onShow() {
			this.init();
		},
		methods: {
			async init() {
				uni.showLoading({
					title: '加载中'
				});
				const res = await postAction('/m/hr/punchPage')
				this.typeDesc = res.data.typeDesc;
				this.typeStatus = res.data.typeStatus;
				this.punchPage = res.data || {}
				uni.hideLoading()
				this.getLocation()
				if (res.data.isBtnGrey) {
					uni.showToast({
						title: typeDesc,
						icon: 'none',
					})
				}
			},
			initTime() {
				this.times = setInterval(() => {
					this.dayTime.time = moment().format('HH:mm')
					this.dayTime.day = moment().format('YYYY年MM月DD日')
					this.dayTime.week = this.getWeek(moment())
				}, 1000)
			},
			getWeek(date) { // 时间戳
				const week = moment(date).day();

				switch (week) {
					case 1:
						return '星期一';
					case 2:
						return '星期二';
					case 3:
						return '星期三';
					case 4:
						return '星期四';
					case 5:
						return '星期五';
					case 6:
						return '星期六';
					case 0:
						return '星期天';
				}
			},
			handleSelected(val) {
				// this.current = val
				if (val == 2) {
					const record = {
						code: 'kaoqin_time_sign',
					}
					uni.navigateTo({
						url: `/application/moduleList?record=${JSON.stringify(record)}`,
					});
				} else {
					this.init()
				}
			},
			handleRefresh() {
				uni.showToast({
					title: '刷新了',
					icon: 'none'
				})
			},
			handleClock() {
				const that = this
				uni.showModal({
					title: '确定打卡吗？',
					success: async (e) => {
						if (e.confirm) {
							const params = {
								lng: that.location.longitude,
								lat: that.location.latitude,
								type: that.punchPage.type,
							}
							console.log('that.location', that.location);
							console.log('params', params);
							const res = await postFormAction('/m/hr/punch', params);
							console.log('res', res);
							if (res.code == 500) {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							} else {
								let result = res.data.result;
								that.punchId = res.data.id;
								let min = res.data.min;
								let desc = '';
								if (result == 1) {
									desc = '迟到' + min + '分钟';
								} else if (result == 2) {
									desc = '早退' + min + '分钟';
								}

								if (result != 0) {
									// that.postRemark(punchId);
									that.handleShowOpen();
								} else {
									uni.showModal({
										title: '提示',
										content: '打卡成功',
										success: function(suc) {
											if (suc.confirm) {
												that.callBack()
											} else if (suc.cancel) {
												that.callBack()
											}
										}
									});
								}
								// uni.showToast({
								// 	title: '已打卡',
								// 	icon: 'none'
								// })
							}
						}
					}
				})
			},

			postRemark(punchId, desc) {
				let that = this;
				uni.showModal({
					title: desc, //提示内容
					placeholderText: '请填写原因', //输入提示
					showCancel: false,
					editable: true,
					success: async function(suc) {
						if (suc.confirm) {
							const {
								content
							} = suc
							if (content == '') {
								uni.showToast({
									title: '请填写原因',
									icon: 'none',
								})
								that.postRemark(punchId, desc);
								return;
							}
							console.log('content', content);
							uni.showLoading({
								title: '加载中'
							});
							const params = {
								id: punchId,
								remark: content,
							}
							console.log('params', params);
							postFormAction('/m/hr/punchRemark', params).then((
									res) => {
									uni.hideLoading()
									uni.showToast({
										icon: "none",
										title: '操作成功',
									});
									that.callBack()
								})
								.catch((e) => {
									uni.showToast({
										icon: "none",
										title: e.message,
									});
								});
						} else if (suc.cancel) {
							this.callBack()
						}
					}
				});
			},

			//打开modal
			handleShowOpen() {
				this.valiFormData.remark = undefined;
				this.modalData.title = '提示';
				this.showOpen = true;
				console.log('valiForm', this.$refs.uForm)
				this.$refs.uForm.resetFields()
				// this.$refs.valiForm.clearValidate();
			},
			//modal回调
			onConfirm() {
				let that = this;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log("this.valiFormData", this.valiFormData, valid)
						uni.showLoading({
							title: '加载中'
						});
						const params = {
							id: that.punchId,
							remark: this.valiFormData.remark,
						}
						console.log('params', params);
						postFormAction('/m/hr/punchRemark', params).then((
								res) => {
								uni.hideLoading()
								uni.showModal({
									title: '提示',
									content: '操作成功',
									success: function(suc) {
										if (suc.confirm) {
											that.callBack()
										} else if (suc.cancel) {
											that.callBack()
										}
									}
								});
							})
							.catch((e) => {
								uni.hideLoading()
								uni.showToast({
									icon: "none",
									title: e.message,
								});
							});

						this.showOpen = false;
					} else {
						console.log('验证失败');
					}
				});
			},

			getLocation() {
				let that = this;
				console.log("开始定位")
				uni.getLocation({
					type: "wgs84", // "gcj02" 需配置sdk才支持
					isHighAccuracy: true, //高精度
					// geocode:true,
					success: async function(res) {
						console.log('getLocation res', res);
						that.location = res
						that.location.distance = await that.GetDistance(that.punchPage.lngLoc, that.punchPage
							.latLoc)
						console.log('that.location.distance', that.location.distance);
						if (that.location.distance * 1000 < (that.punchPage.radius - 0)) {
							that.isDistance = true
						}
					},
					fail(e) {
						console.log("定位失败", e)
						uni.showToast({
							title: '获取位置信息失败，无法使用定位功能',
							icon: 'none',
						})
					}
				});
			},
			//进行经纬度转换为距离的计算
			Rad(d) {
				return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
			},
			//计算距离，经度 纬度
			async GetDistance(lng1, lat1) {
				const res = {
					lat: this.location.latitude,
					lng: this.location.longitude
				}
				console.log(res.lat, res.lng, '自己的位置');
				console.log(lat1, lng1);
				let lat2 = res.lat; //维度
				let lng2 = res.lng; //经度
				var radLat1 = this.Rad(lat1);
				var radLat2 = this.Rad(lat2);
				var a = radLat1 - radLat2;
				var b = this.Rad(lng1) - this.Rad(lng2);
				var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
					Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
				s = s * 6378.137; // EARTH_RADIUS;
				s = Math.round(s * 10000) / 10000; //输出为公里
				//s=s.toFixed(4);
				console.log(s, '公里');
				return s;
			},
			/*返回上一页*/
			callBack() {
				// var pages = getCurrentPages();
				// var currPage = pages[pages.length - 1]; //当前页面
				// var prevPage = pages[pages.length - 2]; //上一个页面
				uni.navigateBack();
			}

		}
	}
</script>
<style lang="less" scoped>
	.clock_in {
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		&_time {
			width: 100%;
			text-align: center;

			.dayTime_time {
				margin: 40upx 0 20upx 0;
				font-size: 80upx;
				font-weight: bold;
			}
		}

		&_summary {
			color: #0293fe;
			text-align: center;
			margin: 30upx 0 30upx 0;
			font-weight: bold;
		}

		.clock_in_statistics {
			display: flex;

			&_left {
				width: 50%;
				padding-right: 40upx;
				border-right: 1px solid #ccc;
				display: flex;
				flex-direction: column;
				align-items: flex-end;

				&_label {
					width: 100px;
					text-align: center;
				}

				&_value {
					margin-bottom: 10upx;
					width: 100px;
					text-align: center;
				}
			}

			&_right {
				width: 50%;
				padding-left: 40upx;

				&_label {
					width: 284upx;
					text-align: center;
				}

				&_value {
					margin-bottom: 10upx;
					width: 284upx;
					text-align: center;
				}
			}
		}

		.clock_in_refresh {
			text-align: center;
			margin-top: 40upx;
		}

		.clock_in_menu {
			display: flex;
			justify-content: space-around;
			padding: 20upx;

			&_box {
				text-align: center;
				color: #e5e5e5;
			}
		}

		.active {
			color: #0094ff;
		}
	}
</style>